import React, { Component } from 'react'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import { Link } from 'react-router'
import { Table, Spin, Form, Row, Col, Input, Button, Dropdown, Menu, Icon, Popconfirm, message, Modal, Select, TreeSelect, Checkbox, Tabs, Tag, Popover, Upload } from 'antd'
import _ from 'lodash'

import Ajax from 'lib/Ajax'
import { addConfig } from 'actions/config'
import AddProjectFile from './addProjectFile'
import { getNewTreeData, findRowData, getNameByCode, getArrayByValue, getArrayByKey, confirmDelete, download } from 'lib/fun'

const ButtonGroup = Button.Group;
const FormItem = Form.Item;
const SelectTreeNode = TreeSelect.TreeNode;
const CheckboxGroup = Checkbox.Group;
const Option = Select.Option;
const TabPane = Tabs.TabPane;
const Dragger = Upload.Dragger;

// 新建编辑
class Edit extends Component {
  constructor(props) {
    super(props);
    this.state = {
      activeKey: '1',   //tab选中
      loading: false,
      tagList: [],
      dicList: [],
      visabled: false,
      rowdata: {},
      projectAttach: [],
      editFileType: "new",
      editFileRowData: {}
    }
  }

  componentDidMount(){
    this.loadTag();
    this.loadDic();
    const { config, addConfig } = this.props;
    if(!config.attachTypeCode){
      // 孤儿类型
      addConfig('attachTypeCode', 33);
    }
  }

  componentWillReceiveProps(nextProps){
    if(!nextProps.visible){
      this.props.form.resetFields();
      this.setState({
        activeKey: '1',
        projectAttach: []
      });
    }else{
      if(nextProps.type == 'edit'){
        if(nextProps.rowdata.projectId&&(!this.props.rowdata.projectId&&this.props.rowdata.projectId != nextProps.rowdata.projectId)){
          this.setState({
            loading: true,
            activeKey: '1'
          });
          this.loadProject(nextProps.rowdata.projectId);
        }
      }else if(this.props.type == 'edit'){
        this.setState({
          activeKey: '1'
        });
      }
      if(!this.props.config.moneyCalculateTypeCode){
        // 发放周期
        this.props.addConfig('moneyCalculateTypeCode',11);
      }
    }
  }

  loadProject = (id)=>{
    var self = this;
    Ajax({
      url: '/project/get',
      data: {
        projectId: id
      },
      success: function(data){
        _.each(data.projectAttach, (item)=>{
          item.randomId = parseInt(Math.random()*1000000);
        });
        self.setState({
          loading: false,
          rowdata: data,
          projectAttach: data.projectAttach||[]
        });
      },
      error: function(error){
        message.error(error);
      }
    });
  }

  loadTag = ()=>{
    var self = this;
    Ajax({
      url: '/projectTag/list',
      data: {},
      success: function(data){
        self.setState({
          tagList: data
        });
      },
      error: function(error){
        message.error(error);
      }
    });
  }

  loadDic = ()=>{
    var self = this;
    Ajax({
      url: '/projectExtensionDic/list',
      data: {},
      success: function(data){
        self.setState({
          dicList: data
        });
      },
      error: function(error){
        message.error(error);
      }
    });
  }

  handleCommit = () => {
    var self = this;
    self.props.form.validateFields((err, values) => {
      if(err == null&&!this.state.loading){
        self.setState({
          loading: true
        });
        const { type, rowdata, address  } = self.props;
        console.log(values);
        if(self.props.type == 'edit'){
          values.projectId = rowdata.projectId;
        }
        values.projectCategoryId = parseInt(values.projectCategoryId);
        values.projectTagList = getArrayByValue(this.state.tagList, values.projectTagList, 'projectTagId');
        values.projectDicList = getArrayByValue(this.state.dicList, values.projectDicList, 'extId');
        values.projectAttach = self.state.projectAttach;
        console.log(JSON.stringify(values));
        Ajax({
          url: '/project/save',
          data: values,
          success: function(data){
            self.setState({
              loading: false
            });
            self.props.onOk(self.props.type, data);
          },
          error: function(error){
            self.setState({
              loading: false
            });
            message.error(error);
          }
        });
      }
    });
  }

  onCancel = ()=>{
    this.setState({
      loading: false
    });
    this.props.onCancel();
  }

  operate = (type, row)=>{
    if(type == 'edit'){
      this.setState({
        visabled: true,
        editFileType: type,
        editFileRowData: row
      });
    }else{
      this.setState({
        visabled: true,
        editFileType: type
      });
    }
  }

  editOk = (type, rowdata)=>{
    var self = this;
    if(type == 'edit'){
      var find = _.find(self.state.projectAttach, (item)=>{
        return item.attachUrl == rowdata.attachUrl
      })
      Object.assign(find, rowdata);
    }else{
      rowdata.randomId = parseInt(Math.random()*1000000);
      self.state.projectAttach.push(rowdata);
    }
    self.setState({
      visabled: false,
      editFileRowData: {},
      projectAttach: self.state.projectAttach
    });
  }
  editCancel = ()=>{
    this.setState({
      visabled: false,
      editFileRowData: {}
    });
  }
  doDelete = (rowdata)=>{
    var self = this;
    _.remove(self.state.projectAttach, (item)=>{
      return rowdata.attachId&&item.attachId == rowdata.attachId||item.randomId == rowdata.randomId
    });
    self.setState({
      projectAttach: self.state.projectAttach
    })
  }

  downloadFile = (obj)=>{
    download(`${obj.attachUrl}`);
  }

  renderProject = ()=>{
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: { span: 10 },
      wrapperCol: { span: 14 },
    };
    const formItemLayout2 = {
      labelCol: { span: 12 },
      wrapperCol: { span: 12 },
    };
    const { visible, type, projectCate, config } = this.props;
    const { rowdata } = this.state;
    const loop = data => data.map((item) => {
      if (item.children&&item.children.length > 0) {
        return <SelectTreeNode title={item.projectCategoryName} key={item.projectCategoryId+""} value={item.projectCategoryId + ""}>{loop(item.children)}</SelectTreeNode>;
      }
      return <SelectTreeNode title={item.projectCategoryName} key={item.projectCategoryId+""} value={item.projectCategoryId + ""} isLeaf={!item.children}/>;
    });
    const treeNodes = loop(projectCate);
    console.log(getArrayByKey(rowdata.projectTagList, 'projectTagId'));
    return (
      <div>
      <Row gutter={20}>
        <Col span={8}>
          <FormItem {...formItemLayout} label="补贴类别">
            {getFieldDecorator("projectCategoryId",{
              initialValue: type == 'edit'?rowdata.projectCategoryId+"":"",
              rules: [{
                required: true, message: '请选择补贴类别',
              }]
            })(
              <TreeSelect>
                {
                  treeNodes
                }
              </TreeSelect>
            )}
          </FormItem>
        </Col>
        <Col span={8}>
          <FormItem {...formItemLayout} label="项目编号">
            {getFieldDecorator("projectCode",{
              initialValue: type == 'edit'?rowdata.projectCode:"",
              rules: [{
                required: true, message: '请输入项目编号',
              }]
            })(
              type == 'edit'?<Input disabled/>:<Input />
            )}
          </FormItem>
        </Col>
        <Col span={8}>
          <FormItem {...formItemLayout} label="项目名称">
            {getFieldDecorator("projectName",{
              initialValue: type == 'edit'?rowdata.projectName:"",
              rules: [{
                required: true, message: '请输入项目名称',
              }]
            })(
              <Input />
            )}
          </FormItem>
        </Col>
      </Row>
      <Row gutter={20}>
        <Col span={8}>
          <FormItem {...formItemLayout} label="项目名称(藏)">
            {getFieldDecorator("projectNameZe",{
              initialValue: type == 'edit'?rowdata.projectNameZe:""
            })(
              <Input />
            )}
          </FormItem>
        </Col>
        <Col span={8}>
          <FormItem {...formItemLayout} label="主管部门">
            {getFieldDecorator("orgCode",{
              initialValue: type == 'edit'?rowdata.orgCode:"",
              rules: [{
                required: true, message: '请选择主管部门',
              }]
            })(
              <Select>
                {
                  (config.orgType||[]).map(function(obj){
                    return (<Option key={obj.dictionaryId} value={ obj.dictionaryCode }>{ obj.dictionaryName }</Option>)
                  })
                }
              </Select>
            )}
          </FormItem>
        </Col>
        <Col span={8}>
          <FormItem {...formItemLayout} label="发放周期">
            {getFieldDecorator("payCycleCode",{
              initialValue: type == 'edit'?rowdata.payCycleCode:"",
              rules: [{
                required: true, message: '请选择发放周期',
              }]
            })(
              <Select>
                {
                  (config.payCycleCode||[]).map(function(obj){
                    return (<Option key={obj.dictionaryId} value={ obj.dictionaryCode }>{ obj.dictionaryName }</Option>)
                  })
                }
              </Select>
            )}
          </FormItem>
        </Col>
      </Row>
      <Row gutter={20}>
        <Col span={8}>
          <FormItem {...formItemLayout} label="发放单位">
            {getFieldDecorator("payUnitCode",{
              initialValue: type == 'edit'?rowdata.payUnitCode:"",
              rules: [{
                required: true, message: '请选择发放单位',
              }]
            })(
              <Select>
                {
                  (config.payUnitCode||[]).map(function(obj){
                    return (<Option key={obj.dictionaryId} value={ obj.dictionaryCode }>{ obj.dictionaryName }</Option>)
                  })
                }
              </Select>
            )}
          </FormItem>
        </Col>
        <Col span={8}>
          <FormItem {...formItemLayout} label="发放对象">
            {getFieldDecorator("payObjCode",{
              initialValue: type == 'edit'?rowdata.payObjCode:"",
              rules: [{
                required: true, message: '请选择发放对象',
              }]
            })(
              <Select>
                {
                  (config.payObjCode||[]).map(function(obj){
                    return (<Option key={obj.dictionaryId} value={ obj.dictionaryCode }>{ obj.dictionaryName }</Option>)
                  })
                }
              </Select>
            )}
          </FormItem>
        </Col>
        <Col span={8}>
          <FormItem {...formItemLayout} label="发放对象描述">
            {getFieldDecorator("payObjStr",{
              initialValue: type == 'edit'?rowdata.payObjStr:""
            })(
              <Input />
            )}
          </FormItem>
        </Col>
      </Row>
      <Row gutter={20}>
        <Col span={8}>
          <FormItem {...formItemLayout} label="金额计算类型">
            {getFieldDecorator("moneyCalculateTypeCode",{
              initialValue: type == 'edit'?rowdata.moneyCalculateTypeCode:"",
              rules: [{
                required: true, message: '请选择金额计算类型',
              }]
            })(
              <Select>
                {
                  (config.moneyCalculateTypeCode||[]).map(function(obj){
                    return (<Option key={obj.dictionaryId} value={ obj.dictionaryCode }>{ obj.dictionaryName }</Option>)
                  })
                }
              </Select>
            )}
          </FormItem>
        </Col>
        <Col span={8}>
          <FormItem {...formItemLayout} label="合计金额计算公式">
            {getFieldDecorator("totalFormula",{
              initialValue: type == 'edit'?rowdata.totalFormula:"",
            })(
              <Input />
            )}
          </FormItem>
        </Col>
        <Col span={8}>
          <FormItem {...formItemLayout} label="补贴金额">
            {getFieldDecorator("subsidyMoney",{
              initialValue: type == 'edit'?rowdata.subsidyMoney:"",
            })(
              <Input />
            )}
          </FormItem>
        </Col>
      </Row>
      <Row gutter={20}>
        <Col span={8}>
          <FormItem {...formItemLayout} label="是否需要乡镇复核">
            {getFieldDecorator("isNeedTownReview",{
              valuePropName: 'checked',
              initialValue: type == 'edit'?rowdata.isNeedTownReview:""
            })(
              <Checkbox />
            )}
          </FormItem>
        </Col>
        <Col span={8}>
          <FormItem {...formItemLayout2} label="是否需要主管部门审批">
            {getFieldDecorator("isNeedOrgReview",{
              valuePropName: 'checked',
              initialValue: type == 'edit'?rowdata.isNeedOrgReview:""
            })(
              <Checkbox />
            )}
          </FormItem>
        </Col>
        <Col span={8}>
          <FormItem {...formItemLayout2} label="是否允许主管部门录入">
            {getFieldDecorator("allowOrgEntry",{
              valuePropName: 'checked',
              initialValue: type == 'edit'?rowdata.allowOrgEntry:""
            })(
              <Checkbox />
            )}
          </FormItem>
        </Col>
      </Row>
      <Row gutter={20}>
        <Col span={12}>
          <FormItem labelCol={{ span: 6 }} wrapperCol={{ span: 18 }} label="项目标签">
            {getFieldDecorator("projectTagList",{
              initialValue: type == 'edit'&&rowdata.projectTagList?getArrayByKey(rowdata.projectTagList, 'projectTagId'):[],
            })(
              <Select
                multiple
              >
                {
                  this.state.tagList.map((item)=>{
                    return (<Option key={item.projectTagId}>{item.projectTagName}</Option>)
                  })
                }
              </Select>
            )}
          </FormItem>
        </Col>
        <Col span={12}>
          <FormItem labelCol={{ span: 6 }} wrapperCol={{ span: 18 }} label="项目扩展属性">
            {getFieldDecorator("projectDicList",{
              initialValue: type == 'edit'&&rowdata.projectDicList?getArrayByKey(rowdata.projectDicList, 'extId'):[],
            })(
              <Select
                multiple
              >
                {
                  this.state.dicList.map((item)=>{
                    return (<Option key={item.extId}>{item.extName}</Option>)
                  })
                }
              </Select>
            )}
          </FormItem>
        </Col>
      </Row>
      <Row gutter={20}>
        <Col span={12}>
          <FormItem labelCol={{ span: 6 }} wrapperCol={{ span: 18 }} label="概述">
            {getFieldDecorator("remark",{
              initialValue: type == 'edit'?rowdata.remark:"",
            })(
              <Input />
            )}
          </FormItem>
        </Col>
      </Row>
      </div>
    )
  }

  renderProjectAttach = ()=>{
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: { span: 18 },
      wrapperCol: { span: 6 },
    };
    const { visible, type } = this.props;
    const { bankCode } = this.props.config;

    const columns = [{
      title: '附件类别',
      dataIndex: 'attachTypeCode',
      render: (text, record) => (<span>{ getNameByCode(this.props.config, 'attachTypeCode', text) }</span>)
    }, {
      title: '附件名称',
      dataIndex: 'attachName'
    }, {
      title: '附件地址',
      dataIndex: 'attachUrl',
      render: (text, record) => {
        return record.projectId?(<a href="javascript:;" title="下载文件" onClick={ this.downloadFile.bind(this, record) }>{ text }</a>):(<span>{ text }</span>)
      }
    }, {
        title: '操作',
        key: 'action',
        render: (text, record) => (<span><a onClick={this.operate.bind(this, 'edit', record)} href="javascript:;">编辑</a> | <a onClick={this.doDelete.bind(this, record)} href="javascript:;">删除</a></span>)
    }];

    return (
      <div>
        <Table 
          columns={columns}
          dataSource={ this.state.projectAttach }
          rowKey="randomId"
          size="small"
          pagination={false}
        />
        <div style={{textAlign:'center',marginTop:15}}>
          <Button type="dashed" onClick={ this.operate.bind(this, 'new') } style={{ width: '100%' }}>
            <Icon type="plus" /> 添加文件
          </Button>
        </div>
      </div>
    )
  }

  render() {
    const { visible, type, rowdata, projectCate, config } = this.props;
    return (<div>
            <Modal 
              title={ type == 'edit'?"修改项目":"新建项目" }
              visible={visible}
              onOk={ this.handleCommit } 
              onCancel={ this.onCancel }
              okText="确定" 
              cancelText="取消"
              width="920px"
            >
              <Spin spinning={this.state.loading}>
                <Form
                  horizontal
                >
                  <Tabs 
                    defaultActiveKey="1" 
                    activeKey={ this.state.activeKey } 
                    onTabClick={ (key)=>{ this.setState({ activeKey: key }) }}
                  >
                    <TabPane tab="项目信息" key="1">
                      { this.renderProject() }
                    </TabPane>
                    <TabPane tab="项目附件" key="2">
                      { this.renderProjectAttach() }
                    </TabPane>
                  </Tabs>
                </Form>
              </Spin>
            </Modal>
            <AddProjectFile
              onOk={ this.editOk }
              onCancel={ this.editCancel }
              visible={ this.state.visabled }
              type = { this.state.editFileType }
              rowdata = { this.state.editFileRowData }
              projectId = { this.state.rowdata.projectId }
            />
            </div>);
  }
}

function mapStateToProps(state) {
  return {
    config: state.config
  }
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators({ addConfig }, dispatch)
}

module.exports = connect(mapStateToProps,mapDispatchToProps)(Form.create()(Edit));
